//
//  JXCommentView.m
//  JiaoX
//
//  Created by yinqy on 15/1/8.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXReplyCommentView.h"
#import "JXNavigationController.h"
#import "UserDefaultsHelper.h"
#import "JXLoginRegistCheckController.h"
#import "EmotionKeyboard.h"
#import "EmotionInfo.h"
#import "EmotionUtil.h"

#define SENDBTN_FONT_SIZE 15


@interface JXReplyCommentView()<UITextFieldDelegate>
{
    UIButton *_button;
    UIButton *_pictureButton;
    UIButton *_emotionButton;
    NSString *_defaultPlaceholder;
}
/**
 *  是否正在切换键盘
 */
@property (nonatomic, assign, getter = isChangingKeyboard) BOOL changingKeyboard;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) EmotionKeyboard *emotionkeyboard;
@end
@implementation JXReplyCommentView


-(instancetype)initWithPlaceholder:(NSString *)placeholder;
{
    self = [super init];
    if (self) {
        _defaultPlaceholder = placeholder;
        self.emotionkeyboard = [EmotionKeyboard keyboard];
        self.emotionkeyboard.width = JXScreenW;
        self.emotionkeyboard.height = 180;
        
        self.fileKeyboard = [[SendFileKeyboard alloc]init];
        
        [self setBackgroundColor:[UIColor whiteColor]];
        self.size = CGSizeMake(JXScreenW, REPLY_VIEW_HEIGHT);
        
        UIView *spliteView = [[UIView alloc]init];
        [spliteView setBackgroundColor:JXColor(204, 204, 204)];
        [spliteView setFrame:CGRectMake(0, 0, self.width, 0.5)];
        [self addSubview:spliteView];
        
        _button = [[UIButton alloc]init];
        [_button setTitleColor:JXColor(204, 204, 204) forState:UIControlStateDisabled];
        [_button setTitleColor:JXThemeColor forState:UIControlStateNormal];
        [_button setEnabled:NO];
        [_button.titleLabel setFont:[UIFont systemFontOfSize:SENDBTN_FONT_SIZE]];
        [_button setTitle:@"发送" forState:UIControlStateNormal];
        [_button setFrame:CGRectMake(self.width-SENDBTN_FONT_SIZE*2-JXPublicInset, 0, SENDBTN_FONT_SIZE*2+1, self.height)];
        [_button addTarget:self action:@selector(replyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_button];
        
        
        _textField = [[UITextField alloc]init];
        [_textField.layer setBorderColor:JXColor(230, 230, 230).CGColor];
        [_textField.layer setBorderWidth:0.7];
        [_textField.layer setCornerRadius:5];
        [_textField setTextColor:JXColor(102, 102, 102)];
        [_textField setFont:[UIFont systemFontOfSize:SENDBTN_FONT_SIZE-1]];
        [_textField setValue:JXColor(153, 153, 153) forKeyPath:@"_placeholderLabel.textColor"];
        [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        [_textField setPlaceholder:placeholder];

        [_textField setFrame:CGRectMake(JXPublicInset, 8, self.width-_button.width-JXPublicInset*3, self.height-16)];
        //添加左边距
        CGRect frame = [_textField frame];
        frame.size.width = 7.0f;
        UIView *leftview = [[UIView alloc] initWithFrame:frame];
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.leftView = leftview;
        
        [self addSubview:_textField];
        
        _emotionButton = [[UIButton alloc]init];
        [_emotionButton setHidden:YES];
        [_emotionButton setBackgroundImage:IMG(@"bg_emotion") forState:UIControlStateNormal];
        [_emotionButton setBackgroundImage:IMG(@"bg_emotion_heighlight") forState:UIControlStateHighlighted];
        [_emotionButton addTarget:self action:@selector(openEmotion) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_emotionButton];
        
        _pictureButton = [[UIButton alloc]init];
        [_pictureButton setHidden:YES];
        [_pictureButton setBackgroundImage:IMG(@"bg_chat_more") forState:UIControlStateNormal];
        [_pictureButton setBackgroundImage:IMG(@"bg_chat_more_heighlight") forState:UIControlStateHighlighted];
        [_pictureButton addTarget:self action:@selector(openFile) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_pictureButton];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectEmotion:) name:NOTI_SELECT_EMOTION object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteEmotion:) name:NOTI_EMOTION_DELETED object:nil];
    }
    return self;
}

-(void)replyBtnClick:(UIButton *)btn{
    if ([self.delegate respondsToSelector:@selector(bottomViewReplyBtnClick:)]) {
        if([self.delegate isKindOfClass:[UIViewController class]]){
            //首先判断是否登录
            NSString *token = [UserDefaultsHelper stringForKey:KEY_APPTOKEN];
            if([Utils isBlankString:token]){//token为空说明没有登录
                JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:[[JXLoginRegistCheckController alloc]init]];
                [(UIViewController *)self.delegate presentViewController:nav animated:YES completion:^{}];
                return;
            }
        }
        [_delegate bottomViewReplyBtnClick:_textField.text];
    }
}

- (void)textFieldDidChange:(UITextField *)textField{
    if([Utils isBlankString:textField.text]){
        [_button setEnabled:NO];
    }else{
        [_button setEnabled:YES];
    }
}

-(void)setPlaceHolder:(NSString *)palceHolder{
    if([Utils isBlankString:palceHolder]){
        [_textField setPlaceholder:_defaultPlaceholder];
    }else {
        [_textField setPlaceholder:palceHolder];
    }
}

-(void)setText:(NSString *)text{
    if([Utils isBlankString:text]){
        [_textField setText:@""];
    }else{
        [_textField setText:text];
    }
    [self textFieldDidChange:_textField];
}

-(void)becomeFirstResponder{
    [_textField becomeFirstResponder];
}

- (void) keyboardWillShow:(NSNotification *)notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    [UIView animateWithDuration:0.25 delay:0 options:0 animations:^{
        self.frame = CGRectMake(0, self.superview.height- keyboardSize.height-REPLY_VIEW_HEIGHT, JXScreenW, REPLY_VIEW_HEIGHT);
    } completion:^(BOOL finished) {}];
}

-(void)keyboardWillHide:(NSNotification*)notif
{
    [UIView animateWithDuration:0.1 delay:0 options:0 animations:^{
        self.frame = CGRectMake(0, self.superview.height-REPLY_VIEW_HEIGHT, JXScreenW, REPLY_VIEW_HEIGHT);
    } completion:^(BOOL finished) {
    }];
}



/**
 *  是否显示表情与键盘切换的按钮
 *
 *  @param showEmotion
 */
-(void)setShowEmotion:(BOOL)showEmotion{
    if (showEmotion) {

        
        [_pictureButton setSize:_pictureButton.currentBackgroundImage.size];
        [_pictureButton setCenterY:_textField.centerY];
        [_pictureButton setX:10];
        
        [_emotionButton setSize:_emotionButton.currentBackgroundImage.size];
        [_emotionButton setCenterY:_textField.centerY];
        [_emotionButton setX:CGRectGetMaxX(_pictureButton.frame)+10];
        
        [_textField setX:CGRectGetMaxX(_emotionButton.frame)+10];
        [_textField setWidth:self.width-_button.width-10-10-_textField.x];
        [_emotionButton setHidden:NO];
        [_pictureButton setHidden:NO];
    }else{
        [_emotionButton setHidden:YES];
        [_pictureButton setHidden:YES];
        [_textField setX:10];
        [_textField setWidth:self.width-_button.width-JXPublicInset*3];
    }
}


/**
 *  打开表情
 */
- (void)openEmotion
{
    // 正在切换键盘
    self.changingKeyboard = YES;
    
    if (self.textField.inputView && [self.textField.inputView isKindOfClass:[EmotionKeyboard class]]) {
        // 当前显示的是自定义键盘，切换为系统自带的键盘
        self.textField.inputView = nil;
        // 显示表情图片
        [self setShowEmotionButton:YES];
    } else { // 当前显示的是系统自带的键盘，切换为自定义键盘
        // 如果临时更换了文本框的键盘，一定要重新打开键盘
        self.textField.inputView = self.emotionkeyboard;
        // 不显示表情图片
        [self setShowEmotionButton:NO];
        [self setShowFileButton:YES];
    }
    
    // 关闭键盘
    [self.textField resignFirstResponder];
    
    // 更换完毕完毕
    self.changingKeyboard = NO;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 打开键盘
        [self.textField becomeFirstResponder];
    });
}

/**
 *
 */
-(void)openFile{
    // 正在切换键盘
    self.changingKeyboard = YES;
    // 显示表情图片
    if (self.textField.inputView && [self.textField.inputView isKindOfClass:[SendFileKeyboard class]]) {
        // 当前显示的是自定义键盘，切换为系统自带的键盘
        self.textField.inputView = nil;
        // 显示发送文件的图片
        [self setShowFileButton:YES];
    }else{
        // 当前显示的是系统自带的键盘，切换为自定义键盘
        // 如果临时更换了文本框的键盘，一定要重新打开键盘
        self.textField.inputView = self.fileKeyboard;
        // 不显示表情图片
        [self setShowFileButton:NO];
        [self setShowEmotionButton:YES];
    }
    // 关闭键盘
    [self.textField resignFirstResponder];
    
    // 更换完毕完毕
    self.changingKeyboard = NO;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 打开键盘
        [self.textField becomeFirstResponder];
    });
}

-(void)setShowEmotionButton:(BOOL)showEmotionButton{
    if (showEmotionButton) {
        [_emotionButton setBackgroundImage:IMG(@"bg_emotion") forState:UIControlStateNormal];
        [_emotionButton setBackgroundImage:IMG(@"bg_emotion_heighlight") forState:UIControlStateHighlighted];
    }else{
        [_emotionButton setBackgroundImage:IMG(@"bg_keyboard") forState:UIControlStateNormal];
        [_emotionButton setBackgroundImage:IMG(@"bg_keyboard_heighlight") forState:UIControlStateHighlighted];
    }
}

-(void)setShowFileButton:(BOOL)showFileButton{
    if (showFileButton) {
        [_pictureButton setBackgroundImage:IMG(@"bg_chat_more") forState:UIControlStateNormal];
        [_pictureButton setBackgroundImage:IMG(@"bg_chat_more_heighlight") forState:UIControlStateHighlighted];
    }else{
        [_pictureButton setBackgroundImage:IMG(@"bg_keyboard") forState:UIControlStateNormal];
        [_pictureButton setBackgroundImage:IMG(@"bg_keyboard_heighlight") forState:UIControlStateHighlighted];
    }
}
-(void)selectEmotion:(NSNotification *)noti{
    EmotionInfo *info = noti.userInfo[KEY_SELECT_EMOTION];
    _textField.text = [_textField.text stringByAppendingString:info.chs];
    [self textFieldDidChange:self.textField];
}

-(void)deleteEmotion:(NSNotification *)noti{
    if (_textField.selectedTextRange.empty) {
        //Find the last thing we may input and delete it. And RETURN
        NSString *text = [self.textField textInRange:[self.textField textRangeFromPosition:self.textField.beginningOfDocument toPosition:self.textField.selectedTextRange.start]];
        NSArray *emotions = [[EmotionUtil sharedInstance] getDefaultEmotion];
            for (EmotionInfo *item in emotions) {
                if ([text hasSuffix:item.chs]) {
                    __block NSUInteger composedCharacterLength = 0;
                    [item.chs enumerateSubstringsInRange:NSMakeRange(0, item.chs.length)
                                                         options:NSStringEnumerationByComposedCharacterSequences
                                                      usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
                                                          composedCharacterLength++;
                                                      }];
                    
                    UITextRange *rangeToDelete = [self.textField textRangeFromPosition:[self.textField positionFromPosition:self.textField.selectedTextRange.start offset:-composedCharacterLength] toPosition:self.textField.selectedTextRange.start];
                    if (rangeToDelete) {
                        [self replaceTextInRange:rangeToDelete withText:@""];
                        return;
                    }
                }
            }
        
        //If we cannot find the text. Do a delete backward.
        UITextRange *rangeToDelete = [self.textField textRangeFromPosition:self.textField.selectedTextRange.start toPosition:[self.textField positionFromPosition:self.textField.selectedTextRange.start offset:-1]];
        [self replaceTextInRange:rangeToDelete withText:@""];
    } else {
        [self replaceTextInRange:self.textField.selectedTextRange withText:@""];
    }
}

- (void)replaceTextInRange:(UITextRange *)range withText:(NSString *)text {
    if (range && [self textInputShouldReplaceTextInRange:range replacementText:text]) {
        [self.textField replaceRange:range withText:text];
    }
}

- (BOOL)textInputShouldReplaceTextInRange:(UITextRange *)range replacementText:(NSString *)replacementText {
    
    BOOL shouldChange = YES;
    
    NSInteger startOffset = [self.textField offsetFromPosition:self.textField.beginningOfDocument toPosition:range.start];
    NSInteger endOffset = [self.textField offsetFromPosition:self.textField.beginningOfDocument toPosition:range.end];
    NSRange replacementRange = NSMakeRange(startOffset, endOffset - startOffset);
    
    if ([self.textField isKindOfClass:UITextView.class]) {
        UITextView *textView = (UITextView *)self.textField;
        if ([textView.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]){
            shouldChange = [textView.delegate textView:textView shouldChangeTextInRange:replacementRange replacementText:replacementText];
        }
    }
    
    if ([self.textField isKindOfClass:UITextField.class]) {
        UITextField *textField = (UITextField *)self.textField;
        if ([textField.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
            shouldChange = [textField.delegate textField:textField shouldChangeCharactersInRange:replacementRange replacementString:replacementText];
        }
    }
    
    return shouldChange;
}


-(void)resetKeyBoard{
    // 当前显示的是自定义键盘，切换为系统自带的键盘
    self.textField.inputView = nil;
    // 显示发送文件的图片
    [self setShowFileButton:YES];
    // 显示表情图片
    [self setShowEmotionButton:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
